package com.ease.concurrent.threadpool.mrbird;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: chenhs
 * @date: Created in 6:59 2020/3/15
 **/
public class PolicyTest {

    public static void main(String[] args) {
        // CallerRunsPolicy策略：由调用线程处理该任务
        //ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.CallerRunsPolicy());

        // DiscardOldestPolicy策略：丢弃最早被放入到线程队列的任务，将新提交的任务放入到线程队列末端
        //ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.DiscardOldestPolicy());

        // DiscardPolicy策略：直接丢弃新的任务，不抛异常
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.DiscardPolicy());


        threadPoolExecutor.execute(new shortTask("任务1"));
        threadPoolExecutor.execute(new longTask("任务2"));
        threadPoolExecutor.execute(new longTask("任务3"));
        threadPoolExecutor.execute(new shortTask("任务4"));
        threadPoolExecutor.execute(new shortTask("任务5"));

        threadPoolExecutor.shutdown();
    }

    static class shortTask implements Runnable {

        private String name;

        public shortTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(Thread.currentThread().getName() + "执行shortTask-name-" + name + "完毕");
            } catch (InterruptedException e) {
                System.err.println("shortTask执行过程中被打断" + e.getMessage());
            }
        }
    }

    static class longTask implements Runnable {
        private String name;

        public longTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(5);
                System.out.println(Thread.currentThread().getName() + "执行longTask-name-" + name + "完毕");
            } catch (InterruptedException e) {
                System.err.println("longTask执行过程中被打断" + e.getMessage());
            }
        }
    }

}
